package org.vdab.projects.tasks.client.gui;

import org.vdab.projects.tasks.client.entities.ClientTaskList;
import org.vdab.projects.tasks.client.gui.widgets.EntityListWidget;
import org.vdab.projects.tasks.client.util.DelayedList;
import org.vdab.projects.tasks.client.util.ICommand;
import org.vdab.projects.tasks.client.util.ICommandWithReturn;
import org.vdab.projects.tasks.client.util.MessageGuard;
import org.vdab.projects.tasks.shared.entities.ITask;
import org.vdab.projects.tasks.shared.entities.impl.Task;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;

public class TaskListWidget extends Composite {

	private static TaskListWidgetUiBinder uiBinder = GWT
			.create(TaskListWidgetUiBinder.class);

	interface TaskListWidgetUiBinder extends UiBinder<Widget, TaskListWidget> {
	}

	public TaskListWidget() {
		MessageGuard.Log("in TaskListWidget ctr");
		initWidget(uiBinder.createAndBindUi(this));
	}
	
	private ClientTaskList myTaskList;
	
	private DelayedList<ITask> myTasks = new DelayedList<ITask>(); 

	@UiField Label lblName;
	
	@UiField EntityListWidget<ITask, TaskWidget> tasksList = new EntityListWidget<ITask, TaskWidget>();
	
	@UiField Button btnAddTask;

	public TaskListWidget set(ClientTaskList tl) throws Exception {
		if(tl==null){
			MessageGuard.Log("tl == null");
			this.lblName.setText("NULL");
		}
		this.myTaskList = tl;
		bind();
		for(ITask t: myTaskList.getTasks()){
			myTasks.add(t);
		}		
		update();		
		return this;
	}

	private void update() throws Exception {
		this.lblName.setText("Widget: " + myTaskList.getDisplayText());
	}
	
	@UiHandler("btnAddTask")
	public void onAddTaskClick(ClickEvent e){
		try{
			ITask task = this.myTaskList.createNewTask();
			this.myTasks.add(task);
		}catch(Exception ex){
			MessageGuard.Log(ex.getLocalizedMessage());
		}
	}
	
	private void bind() throws Exception{		
		this.tasksList.bind(myTasks, new ICommandWithReturn<ITask, TaskWidget>() {			
			@Override
			public TaskWidget execute(ITask entity) throws Exception {				
				return new TaskWidget(entity);
			}
		}); 
	}
}
